var points = [];
var ren;
var res;
var buildp, getli, clearm, getm, outs, timerk, clearrd; // funkcie
var getD = 0;
var map;
var rozdiel = 2;
var zac = null;
var kon = null;
var timer;
var markers = [];
var marker;
var directionsDiv = document.getElementById("directions");
var locationsAdded = 1;

var mobilne = 0, // definicia pocyu udalosti
    nehody = 0,
    hliadky = 0,
    radary = 0;

/// slider veci
var prvy, druhy;

var d = new Date();
var datum = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
var diff = Math.floor((Date.parse(datum) - Date.parse('2012-07-29')) / 86400000);

///

function initialize() {

    var latlng = new google.maps.LatLng(48.75, 19.70);
    var infowindow = new google.maps.InfoWindow();

    var array = [];
    var options = {
        zoom:7,
        center:latlng,
        mapTypeId:google.maps.MapTypeId.ROADMAP,
        draggableCursor:"crosshair"
    };

    map = new google.maps.Map(document.getElementById("map"), options);

    var autocomplete = new google.maps.places.Autocomplete(document.getElementById('location'), {});


    ren = new google.maps.DirectionsRenderer({'draggable':true, 'avoidHighways':true, 'avoidTolls':true});
    ser = new google.maps.DirectionsService();

    ren.setPanel(document.getElementById('directions'));

    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var place = autocomplete.getPlace();
        getli(place.geometry.location, $('#location').val());
        map.setCenter(place.geometry.location);
        $("#location").val("");
    });

    google.maps.event.addListener(ren, 'directions_changed', function () {
        getD++; // inkrement!
        if (getD > 1) { // kvoli opakovanemu zapisu!

            clearm();
            getm(ren.directions, rozdiel);
            outs(ren.directions);

        }

    });

    google.maps.event.addListener(map, "click", function (location) {
        getli(location.latLng, "Pozícia " + locationsAdded);
        locationsAdded++;
        getD = 0;
    });

    outs = function outputStats(result) {


        var distance = 0;
        var time = 0;
        var theRoute = result.routes[0];

        for (var i = 0; i < theRoute.legs.length; i++) {
            var theLeg = theRoute.legs[i];
            distance += theLeg.distance.value;
            time += theLeg.duration.value;
        }

        if ((Math.round(time / 60)) > 60) {
            time_edited = Math.floor(time / 3600);
            minutes = ((Math.round(time / 60)) - time_edited * 60);
            $("#duration").text("Celkový čas: " + time_edited + " hodín a " + minutes + " minút.");
        } else {
            $("#duration").text("Celkový čas: " + Math.round(time / 60) + " minút.");
        }

        $("#distance").text("Vzdialenosť: " + showDistance(distance));
        $("#average_speed").html("Priemerná rýchlosť: " + Math.round((distance / 1000) / (time / 3600)) + "km/h<br /><span id='skry'>Skryt/zobrazit data</span>");

        var legs = result.routes[0].legs.length;
        var data = 'kilometres=' + showDistanceM(distance) +
            '&avg_speed=' + Math.round((distance / 1000) / (time / 3600)) +
            '&time_driven=' + Math.round(time / 60) +
            '&s_latitude=' + points[0].LatLng.lat() +
            '&s_longitude=' + points[0].LatLng.lng() +
            '&e_latitude=' + points[points.length - 1].LatLng.lat() +
            '&e_longitude=' + points[points.length - 1].LatLng.lng() +
            '&start_loc=' + result.routes[0].legs[0].start_address +
            '&end_loc=' + result.routes[0].legs[legs - 1].end_address;

        $.ajax(
            {
                type:'POST',
                data:data,
                url:'insert',
                success:function (response) {

                }
            });
    }


    getm = function getMarkers(res, rozdiel) {


        array_checked = [];

        $('.checkbox_route').each(function (index) {
            if ($(this).hasClass('checkbox_route_checked')) {
                array_checked.push(index + 1);
            }
        });

        array = [];
        var xi = 0;
        for (o = 0; o < res.routes[0].legs.length; o++) {
            for (p = 0; p < res.routes[0].legs[o].steps.length; p++) {
                for (r = 0; r < res.routes[0].legs[o].steps[p].path.length; r++) {

                    if (r == 0) {
                        coord1 = (res.routes[0].legs[o].steps[p].path[r].Za).toFixed(5);
                        coord2 = (res.routes[0].legs[o].steps[p].path[r].Ya).toFixed(5);
                        array[0] = [];
                        array[0][0] = coord1;
                        array[0][1] = coord2;
                    }
                    if (r > 0) {
                        if ((res.routes[0].legs[o].steps[p].path[r].Ya).toFixed(5) != coord1 &&
                            (res.routes[0].legs[o].steps[p].path[r].Ya).toFixed(5) != coord2) {
                            xi++;
                            array[xi] = [];
                            array[xi][0] = (res.routes[0].legs[o].steps[p].path[r].Za).toFixed(5);
                            array[xi][1] = (res.routes[0].legs[o].steps[p].path[r].Ya).toFixed(5);
                        }
                    }
                    coord1 = (res.routes[0].legs[o].steps[p].path[r].Za).toFixed(5);
                    coord2 = (res.routes[0].legs[o].steps[p].path[r].Ya).toFixed(5);
                }
            }
        }

        $.ajax(
            {
                type:'POST',
                data:{ 'data':array, 'zac':zac, 'kon':kon, 'array_checked':array_checked},
                url:CI.base_url + "routes/loadRoute/" + rozdiel,
                beforeSend:function () {

                    $('#loader').show();
                    timerk();
                    $('body').css('overflow', 'hidden');
                },
                complete:function () {
                    $('#loader').hide();
                    clearInterval(timer);
                    $('body').css('overflow', 'visible');

                },
                error:function () {
                    $('#loader').hide();
                    $('body').css('overflow', 'visible');
                },
                success:function (response) {

                    var obj = jQuery.parseJSON(response);
                    if (obj != null) {

                        $.each(obj.markers, function (i, marker_g) {
                            var marker = new google.maps.Marker(
                                {
                                    position:new google.maps.LatLng(marker_g.latitude, marker_g.longitude),
                                    draggable:true,
                                    icon:CI.base_url + "css/images/" + marker_g.icon
                                });
                            markers.push(marker);
                            marker.setMap(map);
                            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                                return function () {
                                    infowindow.setContent((marker_g.count));
                                    infowindow.open(map, this);

                                }
                            })(marker, i));
                        });

                        // zac. poctu
                        $.each(obj.overal_status, function (i, type) {
                            radary = type.rad;
                            hliadky = type.hl;
                            nehody = type.neh;
                            mobilne = type.mob;
                        });
                        $('#summary_route').fadeIn(1500);
                        // koniec poctu
                        $.ajax({
                            type:'POST',
                            data:{ 'rad':radary, 'hl':hliadky, 'neh':nehody, 'mob':mobilne},
                            url:'update_insert',
                        });
                    } else {
                        $('#summary_route').hide();
                    }


                    ren.setMap(map);
                    ren.setPanel(document.getElementById('directions'));

                    // ren.setPanel(directionsDiv);
                }
            });
    }


    buildp = function BuildPoints() {
        clearm();
        var html = "";
        for (var i = 0; i < points.length; i++) {
            var marker = new google.maps.Marker({position:points[i].LatLng, title:points[i].LocationName});
            markers.push(marker);
            marker.setMap(map);

            html += "<tr><td>" + points[i].LocationName + "</td><td>" + roundNumber(points[i].LatLng.lat(), 6) + "</td><td>" +
                roundNumber(points[i].LatLng.lng(), 6) + '</td><td><button class="achbutton' + i + '">X</button></td></tr>';
        }
        $("#locations tbody").html(html);
    }

    getli = function GetLocationInfo(latlng, locationName) {
        if (latlng != null) {
            var point = {LatLng:latlng, LocationName:locationName};
            points.push(point);
            buildp();
        }
    }

    clearm = function clearMarkers() {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        }
        markers = [];
    }

    timerk = function timeriK() {

        var x = 0;
        timer = setInterval(countDownNumbers, 100);

        function countDownNumbers() {
            if (x < 5000) {
                x++;
                $('#routeChanges').text('Čas výpočtu: ' + ((x / (10))).toFixed(1) + 's');
            }
        }
    }

    clearrd = function ClearRouteDetails() {
        ren.setMap(null);
        ren.setPanel(null);
        $("#distance").html("");
        $("#duration").html("");
    }


}

//// JQUERY VECI

//// JQUERY VECI

jQuery(document).ready(function () {


    $('tbody tr td button').live('click', function () {
        var thhis = $(this).attr('class');
        var poz = thhis.substr(9, 2);
        points.splice(poz, 1);
        buildp();
        ClearRouteDetails();
        getD = 0;
    });

    $('#get_dir').click(function () {
        GetDirections();
    });

    $('.checkbox_route_left[title]').qtip({
        content:false,

        style:{
            tip:{ // Now an object instead of a string
                corner:'topLeft', // We declare our corner within the object using the corner sub-option
                color:'#6fccff',
                size:{
                    x:8, // Be careful that the x and y values refer to coordinates on screen, not height or width.
                    y:8 // Depending on which corner your tooltip is at, x and y could mean either height or width!
                }
            }, 'font-size':10, color:'gray'  },
        position:{
            target:'mouse'
        }  });

    $('#more_sett').click(function () {
        $('#additionalSettings').slideToggle('slow');
        var val = $('#more_sett').html();
        if (val === 'Viac nastavení') {
            $('#more_sett').text('Menej nastavení');
        }
        else {
            $('#more_sett').text('Viac nastavení');
        }
    });

    $('.checkbox_route').mouseover(function () {
        $(this).css('cursor', 'pointer');
        $(this).css('text-decoration', 'underline');
    }).mouseout(function () {
            $(this).css('text-decoration', 'none');
        });
    $('.checkbox_route').click(function () {
        $(this).toggleClass('checkbox_route_checked');
    });

    $('.checkbox_route_left').mouseover(function () {
        $(this).css('cursor', 'pointer');
        $(this).css('text-decoration', 'underline');
    }).mouseout(function () {
            $(this).css('text-decoration', 'none');
        });
    $('.checkbox_route_left').click(function () {
        $(this).toggleClass('checkbox_route_checked');
    });


    function AddLocation() {
        var localSearch = new GlocalSearch();
        localSearch.setSearchCompleteCallback(null,
            function () {
                if (localSearch.results[0]) {
                    var results = localSearch.results[0];
                    var latLong = new google.maps.LatLng(results.lat, results.lng);

                    getli(latLong, $('#location').val());
                    map.setCenter(latLong);
                    getD = 0;
                    $("#location").val("");
                } else {

                    alert("Location not found");
                }
            });

        localSearch.execute(document.getElementById("location").value);
    }


    function remove(index) {
        points = [];
        // BuildPoints();
        // ClearRouteDetails();
        getD = 0;

    }

    $('#search_today').click(function () {
        if (getD < 1) {
            jAlert("<div style='text-align:justify;'>Pred týmto krokom musíte mať vytvorenú trasu.<br /> Vyberte si aspoň dva body a zvoľte <span style='color:red;'>'Nájsť trasu'</span>.</div>", "Chýbajúca trasa!");

            return;
        }
        $('#slider1').slider(
            { values:[diff, diff]});

        function convertValue() {
            var d = new Date();
            var day = d.getDate();
            var month = d.getMonth() + 1;
            var yy = d.getFullYear();

            return day + ". " + month + ". " + yy;
        }

        $("#vypisDate").html("Od: " + convertValue() + "<br />Do: " + convertValue());
        zac = convertValue();
        kon = convertValue();
        clearMarkers();
        getMarkers(ren.directions, 1);
        outputStats(ren.directions);
    });

    $('#search_yesterday').click(function () {
        if (getD < 1) {
            jAlert("<div style='text-align:justify;'>Pred týmto krokom musíte mať vytvorenú trasu.<br /> Vyberte si aspoň dva body a zvoľte <span style='color:red;'>'Nájsť trasu'</span>.</div>", "Chýbajúca trasa!");
            return;
        }
        $('#slider1').slider(
            { values:[diff - 1, diff - 1]});

        Date.prototype.addDays = function (n) {
            var time = this.getTime();
            var changedDate = new Date(time + (n * 24 * 60 * 60 * 1000));
            this.setTime(changedDate.getTime());

            return this;
        };

        function convertValue(druhy, prvy) {
            var d = new Date();
            d.addDays((druhy - prvy));
            var day = d.getDate();
            var month = d.getMonth() + 1;
            var yy = d.getFullYear();

            return day + ". " + month + ". " + yy;
        }

        $("#vypisDate").html("Od: " + convertValue(diff, diff - 1) + "<br />Do: " + convertValue(diff, diff - 1));
        zac = convertValue(diff, diff - 1);
        kon = convertValue(diff, diff - 1);
        clearMarkers();
        getMarkers(ren.directions, 1);
        outputStats(ren.directions);
    });

    $('#search_lastweek').click(function () {
        if (getD < 1) {
            jAlert("<div style='text-align:justify;'>Pred týmto krokom musíte mať vytvorenú trasu.<br /> Vyberte si aspoň dva body a zvoľte <span style='color:red;'>'Nájsť trasu'</span>.</div>", "Chýbajúca trasa!");
            return;
        }
        $('#slider1').slider(
            { values:[diff - 7, diff]});

        Date.prototype.addDays = function (n) {
            var time = this.getTime();
            var changedDate = new Date(time + (n * 24 * 60 * 60 * 1000));
            this.setTime(changedDate.getTime());

            return this;
        };

        function convertValue(druhy, prvy) {
            var d = new Date();
            d.addDays(-(druhy - prvy));
            var day = d.getDate();
            var month = d.getMonth() + 1;
            var yy = d.getFullYear();

            return day + ". " + month + ". " + yy;
        }

        $("#vypisDate").html("Od: " + convertValue(diff, diff - 7) + "<br />Do: " + convertValue(diff, diff));
        zac = convertValue(diff, diff - 7);
        kon = convertValue(diff, diff);
        clearMarkers();
        getMarkers(ren.directions, 8);
        outputStats(ren.directions);
    });


    function br(element) {
        if ($(element).attr('class') == "checkbox_route_left checkbox_route_checked") {
            return true;
        } else {

            return false;
        }
    }


    //////////////////


    function hideMarkers() {
        for (var i = 0; i < markers.length; i++) {

            markers[i].setMap(null);
        }
    }

    function showMarkers() {
        for (var i = 0; i < markers.length; i++) {

            markers[i].setMap(map);
        }
    }


    function ClearPolyLine() {
        points = [];
        buildp();
        clearrd();
    }

    $('#delete_route').click(function () {
        clearm();
        ClearPolyLine();
        clearrd();
        getD = 0;
        locationsAdded = 1;
        map.setCenter(new google.maps.LatLng(48.75, 19.70));
        map.setZoom(7);
    });

    ///// ROUTE SUMMARY

    $('#summary_route').qtip(
        {

            api:{
                beforeShow:function () {


                    // var content = this.elements.target.children(".error-tooltip");
                    // if(content.length > 0) {
                    this.updateContent("Mobilné radary: " + mobilne + "<br />" + "Radary: " + radary + "<br />" + "Nehody: " + nehody + "<br />" + "Hliadky: " + hliadky + "<br />  <div id=\"chart_div\" style=\"width: 200px; height: 100px;\"></div>");
                    // return true;
                    // }
                }
             
            },
            position:{ target:'mouse'},
            show:{ when:'click', solo:true},
            style:{
                classes: 'radar_qtip',
                width : 50,
                tip:{ // Now an object instead of a string
                    corner:'topLeft', // We declare our corner within the object using the corner sub-option
                    color:'red',
                    size:{
                        x:3, // Be careful that the x and y values refer to coordinates on screen, not height or width.
                        y:3 // Depending on which corner your tooltip is at, x and y could mean either height or width!
                    }
                }, 'font-size':11, color:'#222222'}
        });


    /////////// SLIDERSSS

    $("#vypisDate").html("<b>Filter </b>udalosti za posledné dva dni <img src='" + CI.base_url + "css/images/ok_tick.png' style='14px;width:14px;'>");
    $('#slider1').slider(
        {
            min:0,
            max:diff,
            range:true,
            values:[diff - 2, diff],
            start:function (event, ui) {
                prvy = ui.values[0];
                druhy = ui.values[1];
            },

            slide:function (event, ui) {
                var d = new Date();

                var day = d.getDate();
                var month = d.getMonth() + 1;
                var yy = d.getFullYear();

                Date.prototype.addDays = function (n) {
                    var time = this.getTime();
                    var changedDate = new Date(time + (n * 24 * 60 * 60 * 1000));
                    this.setTime(changedDate.getTime());

                    return this;
                };


                function convertValue(param) {
                    var d = new Date();
                    d.addDays(-(diff - ui.values[ param ]));
                    var day = d.getDate();
                    var month = d.getMonth() + 1;
                    var yy = d.getFullYear();
                    return day + ". " + month + ". " + yy;
                }


                if (ui.values[1] - ui.values[0] > 7) {
                    if (ui.values[0] < prvy) {
                        $('#slider1').slider({values:[ui.values[0], ui.values[0] + 7]});
                        $("#vypisDate").html("Od: " + convertValue(0) + "<br />Do: " + convertValue(1));
                    } else if (ui.values[1] > druhy) {
                        $('#slider1').slider({values:[ui.values[1] - 7, ui.values[1]]});
                        $("#vypisDate").html("Od: " + convertValue(0) + "<br />Do: " + convertValue(1));
                    } else {
                        $("#vypisDate").html("Od: " + convertValue(0) + "<br />Do: " + convertValue(1));
                    }
                } else {

                    $("#vypisDate").html("Od: " + convertValue(0) + "<br />Do: " + convertValue(1));
                }
                zac = convertValue(0);
                kon = convertValue(1);
                rozdiel = ui.values[1] - ui.values[0];
            },
            change:_.debounce(function (event, ui) {
                Date.prototype.addDays = function (n) {
                    var time = this.getTime();
                    var changedDate = new Date(time + (n * 24 * 60 * 60 * 1000));
                    this.setTime(changedDate.getTime());

                    return this;
                };

                var dd = new Date();
                dd.addDays(-((diff - ui.values[1]) - (diff - ui.values[0])));

                function convertValue(param) {
                    var d = new Date();
                    d.addDays(-(diff - ui.values[ param ]));
                    var day = d.getDate();
                    var month = d.getMonth() + 1;
                    var yy = d.getFullYear();
                    return day + ". " + month + ". " + yy;
                }


                if (ui.values[1] - ui.values[0] > 7) {
                    if (ui.values[0] < prvy) {
                        $('#slider1').slider({values:[ui.values[0], ui.values[0] + 7]});
                        $("#vypisDate").html("Od: " + convertValue(0) + "<br />Do: " + convertValue(1));
                    } else if (ui.values[1] > druhy) {
                        $('#slider1').slider({values:[ui.values[1] - 7, ui.values[1]]});
                        $("#vypisDate").html("Od: " + convertValue(0) + "<br />Do: " + convertValue(1));
                    } else {
                        $("#vypisDate").html("Od: " + convertValue(0) + "<br />Do: " + convertValue(1));
                    }
                } else {

                    $("#vypisDate").html("Od: " + convertValue(0) + "<br />Do: " + convertValue(1));
                }
                zac = convertValue(0);
                kon = convertValue(1);
                rozdiel = (ui.values[1] - ui.values[0]) + 1;
            }, 500),
            stop:function (event, ui) {


            },

        });

    var msie6 = $.browser == 'msie' && $.browser.version < 7;

    if (!msie6) {

        var top = $('#comment').offset().top - parseFloat($('#comment').css('margin-top').replace(/ auto /, 0));
        $(window).scroll(function (event) {
            // what the y position of the scroll is
            var y = $(this).scrollTop();

            // whether that's below the form
            if (y >= top) {
                // if so, ad the fixed class

                $('#comment').addClass('fixed');
            } else {
                // otherwise remove it
                // $('.qtip_profile').qtip('show');

                $('#comment').removeClass('fixed');
            }
        });
    }

    /////////////
    function GetDirections() {

        if (getD == 0) { // LEN PRVE KOLO NACITAVAJ Z DB...
            if (points.length == 0 || points.length == 1) {
                jAlert("Musíte zadať začiatočný a koncový bod!", "Chýbajúce body");
                return false;
            }
            clearm();
            ren.setMap(map);
            ren.setPanel(document.getElementById('directions'));


            var waypts = [];
            var end = points.length - 1;
            var dest = points[end].LatLng;

            if ($('#roundTrip').attr('class') == "checkbox_route_left checkbox_route_checked") {
                end = points.length;
                dest = points[0].LatLng;
            }

            for (var i = 1; i < end; i++) {

                waypts.push({location:points[i].LatLng});
            }

            var request = {
                origin:points[0].LatLng,
                destination:dest,
                waypoints:waypts,
                travelMode:google.maps.DirectionsTravelMode.DRIVING,
                avoidHighways:br('#speedWays'),
                avoidTolls:br('#tollRoads'),
                optimizeWaypoints:br('#optimizeWaypoints')
            };

            ser.route(request, function (res, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    // ren.setDirections(res);
                    ren.setMap(map);
                    ren.setDirections(res);
                    getm(res, rozdiel);
                    outs(res);

                } else {
                    // chyba
                }


            });

        } else {
            clearm();
            getm(ren.directions, rozdiel);
            outs(ren.directions);
        }

    }


});

//// JQUERY VECI
//// JQUERY VECI

window.onload = function () {
    initialize();
}
